package com.clp.protocol.iec104.apdu.asdu.info_obj.info_elem;

import com.clp.protocol.iec104.definition.Tc;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.Objects;

/**
 * 单点遥控信息元素对象
 */
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class C_SC_NA_1_InfoElem extends TcInfoElem {

    /**
     * 命令类型
     */
    private Tc.CmdType cmdType;
    /**
     * 开关状态
     */
    private Tc.OnePointSwitch onePointSwitch;

    @Override
    public C_SC_NA_1_InfoElem initBy(ByteBuf buf) {
        byte[] bytes = new byte[typeTag().getInfoElemBytesLen()];
        buf.readBytes(bytes);
        byte by = bytes[0];
        this.cmdType = Tc.CmdType.gain((by & 0x80) == 0x80 ? 1 : 0);
        this.onePointSwitch = Tc.OnePointSwitch.gain(by & 0x01);
        return this;
    }

    @Override
    public boolean isValid() {
        if (cmdType == null) return false;
        return onePointSwitch != null;
    }

    @Override
    public void writeTo(ByteBuf buf) {
        byte by = 0x00; // 单点遥控信息长度为1字节
        by |= cmdType.getByteMask();
        by |= onePointSwitch.getByteMask();
        buf.writeByte(by & 0xFF);
    }

    @Override
    public Tc.Type type() {
        return Tc.Type.ONE_POINT;
    }

    @Override
    public boolean isSwitchOn() {
        return onePointSwitch == Tc.OnePointSwitch.ON;
    }

    @Override
    public String toString() {
        return "命令类型：" + cmdType + ", 开关状态：" + onePointSwitch;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        C_SC_NA_1_InfoElem that = (C_SC_NA_1_InfoElem) o;
        return cmdType == that.cmdType && onePointSwitch == that.onePointSwitch;
    }

    @Override
    public int hashCode() {
        return Objects.hash(cmdType, onePointSwitch);
    }
}
